import axios from "axios";
const request = axios.create({
  timeout: 10000,
  baseURL: location.protocol + "//" + import.meta.env.VITE_BASE_URL,
  withCredentials: false,
});

request.interceptors.request.use(
  async (config: any) => {
    if (config.method.toUpperCase() === "GET" && !config.params) {
      config.params = {};
    }
    if (config?.data) {
      if ("loading" in config?.data) {
        delete config.data.loading;
      }
      if ("loadingText" in config?.data) {
        delete config.data.loadingText;
      }
    }
    config.headers.contentType = "application/x-www-form-urlencoded";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    return response.data.data;
  },
  (error) => {
    console.log("err:", error.response); // for debug
    if (
      [400021].includes(error?.response?.data?.code) &&
      !window.location.href.includes("/login") //解决已在登录页，接口多次无效token报错跳转
    ) {
      //无效的token参数跳登录
      localStorage.setItem("token", "");
      return;
    }

    if (error?.response?.data?.message) {
      if (
        [505124, 505020, 605001, 505003, 605103, 605004, 400021].includes(
          error?.response?.data?.code
        )
      ) {
        //505124  有未支付订单，这里不需要该呈现
        //605001 游戏已下架
        //605103 该评论已被删除
      } else {
        let urls = error?.response?.config?.url;
        if (
          urls &&
          ["/marketing/exchange/reward", "/user/user/wxUnbindRules"].includes(
            urls
          )
        ) {
          console.log("includes-urls");
        } else {
          console.error(error.response.data.message);
        }
      }
      return Promise.reject(error?.response?.data || error?.response || error);
    }

    if (error.message.includes("timeout")) {
      // 判断请求异常信息中是否含有超时timeout字符串
      console.error("请求超时，请稍后再试");
      return Promise.reject("timeout"); // reject这个错误信息
    }
    return Promise.reject(error);
  }
);

export default request;
